//
// Created by xu on 2024/11/6.
//
#include "SDL.h"
#include "stdbool.h"
#include "stdio.h"


#define MY_LOG(fmt, ...) \
    printf(fmt, __VA_ARGS__); \
    printf("\n");

SDL_Window *gWindow = NULL;
SDL_Surface *gScreenSurface = NULL;
SDL_Surface *gLoadOptimizeSurface = NULL; // 优化后的图片

int SCREEN_WIDTH = 640;
int SCREEN_HEIGHT = 480;

bool init() {
    bool success = true;
    MY_LOG("test log: %s - %d", "hello", 111);
    // 初始化SDL
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        // printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
        MY_LOG("SDL could not initialize! SDL_Error: %s", SDL_GetError());
        success = false;
    } else {
        // 创建窗口
        gWindow = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH,
                                      SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
        if (gWindow == NULL) {
            printf("Window could not be created! SDL_Error: %s\n", SDL_GetError());
            success = false;
        } else {
            //获取窗口的surface
            gScreenSurface = SDL_GetWindowSurface(gWindow);
        }
    }
    return success;
}

bool loadMedia() {
    bool success = true;
    // 加载bmp格式图片
    SDL_Surface *gLoadSurface = NULL;
    gLoadSurface = SDL_LoadBMP("./images/qiuqiu.bmp");
    if (gLoadSurface == NULL) {
        printf("Unable to load image %s! SDL Error: %s\n", "qiuqiu.bmp", SDL_GetError());
        success = false;
    } else {
        gLoadOptimizeSurface = SDL_ConvertSurface(gLoadSurface, gScreenSurface->format, 0);
        if (gLoadOptimizeSurface == NULL) {
            printf("Unable to optimize image %s! SDL Error: %s\n", "qiuqiu.bmp", SDL_GetError());
            success = false;
        }
        // 释放未优化的图片
    }
    return success;
}

void close() {
    SDL_FreeSurface(gLoadOptimizeSurface);
    gLoadOptimizeSurface = NULL;
    SDL_DestroyWindow(gWindow);
    gWindow = NULL;
    SDL_Quit();
}

int main(int argc, char *argv[]) {
    if (!init()) {
        printf("Failed to initialize!\n");
    } else {
        if (!loadMedia()) {
            printf("Failed to load media!\n");
        } else {
            SDL_Rect stretchRect;
            stretchRect.x = 0;
            stretchRect.y = 0;
            stretchRect.w = SCREEN_WIDTH;
            stretchRect.h = SCREEN_HEIGHT;

            // Apply the image
            // SDL_BlitSurface(gLoadOptimizeSurface, NULL, gScreenSurface, NULL);
            SDL_BlitScaled(gLoadOptimizeSurface, NULL, gScreenSurface, &stretchRect);
            // Update the surface
            SDL_UpdateWindowSurface(gWindow);
            // Hack to get window to stay up
            SDL_Event e;
            bool quit = false;
            while (quit == false) { while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) quit = true; }}
        }
    }

    //Free resources and close SDL
    close();

    return 0;
}